#include "BBox.h"
#include "Ray.h"

bool BBox::Hit(const Ray& ray) const
{
    //splt the ray into 6 floats here,
    float originX = ray.m_origin.m_x; //origin
    float originY = ray.m_origin.m_y;
    float originZ = ray.m_origin.m_z;

    float directionX = ray.m_dir.m_x; // direction
    float directionY = ray.m_dir.m_y;
    float directionZ = ray.m_dir.m_z;

    //declare the main values 
    float tx_min, ty_min, tz_min;
    float tx_max, ty_max, tz_max;

    //What if any memer of direction is 0 ?
    //update, solved! (direction != 0 ? direction : 1.0f);
    float a = 1.0f / (directionX != 0 ? directionX : 1.0f);
    if(a >= 0)
    {
        tx_min = (m_minX - originX) * a;
        tx_max = (m_maxX - originX) * a;
    }
    else
    {
        tx_min = (m_maxX - originX) * a;
        tx_max = (m_minX - originX) * a;
    }

    float b = 1.0f / (directionY != 0 ? directionY : 1.0f);
    if(b >= 0)
    {
        ty_min = (m_minY - originY) * b;
        ty_max = (m_maxY - originY) * b;
    }
    else
    {
        ty_min = (m_maxY - originY) * b;
        ty_max = (m_minY - originY) * b;
    }

    float c = 1.0f / (directionZ != 0 ? directionZ : 1.0f);
    if(c >= 0)
    {
        tz_min = (m_minZ - originZ) * c;
        tz_max = (m_maxZ - originZ) * c;
    }
    else
    {
        tz_min = (m_maxZ - originZ) * c;
        tz_max = (m_minZ - originZ) * c;
    }

    float t0, t1;
    //largest entering t value
    if(tx_min > ty_min)
        t0 = tx_min;
    else
        t0 = ty_min;

    if(tz_min > t0)
        t0 = tz_min;

    //same for the smallest exiting value
    if(tx_max < ty_max)
        t1 = tx_max;
    else
        t1 = ty_max;

    if(tz_max < t1)
        t1 = tz_max;

    bool ret = false;
    if(t0 < t1 && t1 > 0.001f)
        ret = true;
    return ret;
}